
package test1.opengl.jasonbu.com.myapplication1;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;

public class GLRender implements GLSurfaceView.Renderer{
    private Context context;    // 应用的上下文句柄

    private MySquare quad = new MySquare();
    private MyTriangle triangle = new MyTriangle();

    // Constructor with global application context
    public GLRender(Context context) {
        this.context = context;
    }

    // Call back when the surface is first created or re-created
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config)
    {
        // 启用阴影平滑
        gl.glShadeModel(GL10.GL_SMOOTH);

        // 设置背景颜色
        gl.glClearColor(0.2f, 0.4f, 0.52f, 1.0f);

        // 设置深度缓存
        gl.glClearDepthf(1.0f);

        // 启用深度测试
        gl.glEnable(GL10.GL_DEPTH_TEST);

        // 所作深度测试的类型
        gl.glDepthFunc(GL10.GL_LEQUAL);

        // 告诉系统对透视进行修正
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
    }

    // Call back after onSurfaceCreated() or whenever the window's size changes
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height)
    {
        if(height == 0) // 防止被零除
        {
            height = 1;
        }

        // 重置当前的视图区域
        gl.glViewport(0, 0, width, height);

        // 选择投影矩阵
        gl.glMatrixMode(GL10.GL_PROJECTION);

        // 重置投影矩阵
        gl.glLoadIdentity();

        // 设置视图区域的大小
        GLU.gluPerspective(gl, 45.0f, (float)width/(float)height,0.1f,100.0f);

        // 选择模型观察矩阵
        gl.glMatrixMode(GL10.GL_MODELVIEW);

        // 重置模型观察矩阵
        gl.glLoadIdentity();
    }

    // Call back to draw the current frame.
    @Override
    public void onDrawFrame(GL10 gl)
    {
        // 清除屏幕和深度缓存
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        // 重置当前的模型观察矩阵
        gl.glLoadIdentity();

        // 左移 1.5 单位，纵深向里移动 6.0
        gl.glTranslatef(-1.5f,0.0f,-6.0f);
        // 画三角形
        triangle.draw(gl);
        // 右移3单位
        gl.glTranslatef(3.0f,0.0f,0.0f);
        // 画四边形
        quad.draw(gl);
    }
}